package com.example.simin_manage.controller;

import com.example.simin_manage.dto.LoginRequest;
import com.example.simin_manage.dto.MemberVO;
import com.example.simin_manage.dto.RegisterRequest;
import com.example.simin_manage.dto.UserResponse;
import com.example.simin_manage.entity.SysDept;
import com.example.simin_manage.entity.SysUser;
import com.example.simin_manage.mapper.DeptMapper;
import com.example.simin_manage.mapper.SysUserMapper;
import com.example.simin_manage.service.UserService;
import com.example.simin_manage.util.HashUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/14
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;
//组员与组长登录
    @PostMapping("/login")
    public Object login(@RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        SysUser user = userService.login(request);
        if (user != null) {
            // 登录成功，将用户 id 写入 session
            httpRequest.getSession().setAttribute("userId", user.getId());
            httpRequest.getSession().setAttribute("username", user.getUsername());
            UserResponse response = new UserResponse();
            response.setId(user.getId().toString()); // ⚡ 转字符串
            response.setUsername(user.getUsername());
            response.setRole(user.getRole());
            response.setNickname(user.getNickname());
            return new Response(200, "登录成功", response);
        } else {
            return new Response(401, "用户名或密码错误", null);
        }
    }
//    组长对组员注册
    @PostMapping("/register")
    public SysUser register(@RequestBody RegisterRequest request) {
        return userService.register(request);
    }

    // 组长登录获取组员列表
    @GetMapping("/members/{leaderId}")
    public Object getMembers(@PathVariable Long leaderId) {
        List<MemberVO> members = userService.getMembersByLeader(leaderId);
        return new Response(200, "查询成功", members);
    }
    /** 根据 ID 查询单个用户 */
//    @GetMapping("/search")
//    public Response search(@RequestParam String keyword, HttpServletRequest request) {
//        Long leaderId = (Long) request.getSession().getAttribute("userId"); // 或者从 token 里取
//        List<SysUser> list = userMapper.searchUsers(keyword, leaderId);
//        return new Response(200, "查询成功", list);
//    }

    /** 更新用户 */
    @PutMapping("/{id}")
    public Response updateUser(@PathVariable Long id, @RequestBody SysUser updateUser) {
        SysUser user = userMapper.selectById(id);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }
        user.setNickname(updateUser.getNickname());
        user.setDailyTarget(updateUser.getDailyTarget());
        user.setStatus(updateUser.getStatus());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        return new Response(200, "修改成功", null); // ✅ 必须返回 JSON
    }

    /** 删除用户 */
    @DeleteMapping("/{id}")
    public Response delete(@PathVariable Long id) {
        int rows = userMapper.deleteById(id);
        return rows > 0 ? new Response(200, "删除成功", null)
                : new Response(404, "用户不存在", null);
    }

//   重置密码
    @PutMapping("/{id}/reset-password")
    public Response resetPassword(@PathVariable("id") Long id,
                                  @RequestBody Map<String, String> body) {
        // 日志调试
        System.out.println("收到前端传入的数据：" + body);
        System.out.println("userMapper 是否为 null: " + (userMapper == null));
        System.out.println("重置密码 ID: " + id);


        if (body == null || !body.containsKey("password")) {
            return new Response(400, "密码不能为空", null);
        }

        String newPwd = body.get("password");
        if (newPwd == null || newPwd.trim().isEmpty()) {
            return new Response(400, "密码不能为空", null);
        }

        String hashed = HashUtil.sha256(newPwd); // 加密
        SysUser user = userMapper.selectById(id);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }
        user.setPassword(hashed);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        return new Response(200, "密码已重置", null);
    }

    // 用户自己修改密码
    @PutMapping("/{id}/change-password")
    public Response changePassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
        String oldPwd = body.get("oldPassword");
        String newPwd = body.get("newPassword");

        if (oldPwd == null || oldPwd.isEmpty() || newPwd == null || newPwd.isEmpty()) {
            return new Response(400, "密码不能为空", null);
        }

        SysUser user = userMapper.selectById(id);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }

        // 验证旧密码
        if (!user.getPassword().equals(HashUtil.sha256(oldPwd))) {
            return new Response(400, "旧密码错误", null);
        }

        user.setPassword(HashUtil.sha256(newPwd));
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        return new Response(200, "密码修改成功", null);
    }
    @GetMapping("/{id}")
    public Response getUser(@PathVariable Long id) {
        SysUser user = userMapper.selectById(id);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }
        // 如果需要部门名称，可以额外查部门表
        SysDept dept = deptMapper.selectById(user.getDeptId());
        Map<String, Object> data = new HashMap<>();
        data.put("id", user.getId());
        data.put("username", user.getUsername());
        data.put("nickname", user.getNickname());
        data.put("deptId", user.getDeptId());
        data.put("dailyTarget",user.getDailyTarget());
        data.put("deptName", dept != null ? dept.getName() : "未分配");
        return new Response(200, "获取成功", data);
    }


    static class Response {
        public int code;
        public String msg;
        public Object data;

        public Response(int code, String msg, Object data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
        }
    }
}